<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Response;
use Simps\MQTT\Client;
use Simps\MQTT\Config\ClientConfig;
class ProcessSendNotify implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $users,$advers;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($users,$advers)
    {
//        dump('processSendNotify');
        $this->users=$users;
        $this->advers=$advers;
        if (empty($this->users) || empty($this->advers)){
//            dump('users或advers为空');
            return;
        }
//        dump($users);
//        dump($advers);

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
//        dump(get_class_methods('Swoole\Coroutine'));
        $config = [
            'userName' => '', // 用户名
            'password' => '', // 密码
            'clientId' => 'laravel', // 客户端id
            'keepAlive' => 0, // 默认0秒，设置成0代表禁用
            'protocolName' => 'MQTT', // 协议名，默认为MQTT(3.1.1版本)，也可为MQIsdp(3.1版本)
            'protocolLevel' => 4, // 协议等级，MQTT3.1.1版本为4，5.0版本为5，MQIsdp为3
            'properties' => [], // MQTT5 中所需要的属性
            'delay' => 3000, // 重连时的延迟时间 (毫秒)
            'maxAttempts' => 5, // 最大重连次数。默认-1，表示不限制
            'swooleConfig' => []
        ];
        $configObj = new ClientConfig($config);

        $mqtt_host = env("MQTT_HOST");

        $mqtt_port = env("MQTT_PORT");

        $client = new Client($mqtt_host, $mqtt_port, $configObj, Client::SYNC_CLIENT_TYPE);

        $client->connect();

        foreach($this->users as $key=>$val){
//            dump($val);
            $client_topic = Redis::Hget("android_id-client_id",$val);
//            dump($client_topic);
            if(!empty($client_topic)){
                $response= $client->publish($client_topic, json_encode($this->advers), 1);

//                dump($response);
            }
        }
        return;
//        $response = $client->publish('simps-mqtt/user001/update', '{"time":' . time() . '}', 1);
    }
}
